/**
 * Created by lz on 2018/1/7.
 */
import React from 'react';
import { isUndefined, deepCopy, isFunction } from '../../utils/Tools';
import classNames from 'classnames';
import Icon from '../Icon';

import './style/index.scss';//引入样式文件
const prefix = 'lz-';
class Tree extends React.Component {
    constructor(props){
        super(props);

        const data = deepCopy(this.props.dataSrc);
        this.state = {
            data
        }
    }

    /**
     * 获取渲染的dom节点列表
     * @param {Array} arr 
     */
    getRenderHtml(arr) {
        const result = arr.map((item) => {
            const result = [];
            const cls = item.className || '';

            result.push(
                <li className={cls} onClick={this.itemClick.bind(this, item)}>
                    <Icon className={item.icon}></Icon>
                    {item.title}
                    {item.components}
                </li>
            );
            if (( isUndefined(item.show) || item.show === true) && item.children) {
               const list = this.getRenderHtml(item.children); 
               result.push(list);
               return result;
            }
            return result;
        });

        return <ul>{result}</ul>;
    }

    /**
     * 每项点击回调
     * @param {obj} item 
     */
    itemClick(item) {
        // 用户自定义相应事件
        const func = this.props.itemClick;
        // 是否可执行默认事件
        let doNext = true;
        if (func && isFunction(func)) {
            // 返回false截断执行
            doNext = func(item);
        }

        if (doNext === false) {
            return;
        }

        // 默认行为，关闭子菜单
        if (item.children) {
            if (isUndefined(item.show)) {
                item.show = false;
            } else {
                item.show = !item.show;
            }
        }
        this.setState({
            data: this.state.data
        });
    }

    render() {
        let {className, left, right, ...others} = this.props;
        className = classNames(className, prefix + 'tree-container');

        const list = this.getRenderHtml(this.props.dataSrc);
        return <div className={className} {...others}>
            {
                list
            }
        </div>
    }
}

export default Tree;